#!/usr/bin/python
# -*- coding: utf-8 -*-
#用于访问OKEX 期货REST API
from vnpy.api.okex.HttpMD5Util import buildMySign,httpGet,httpPost
OKEX_FUTURE_HOST = 'www.okex.com'                           # OKEX 期货REST地址

class OKCoinFuture:
    def __init__(self,url,apikey,secretkey):
        self.__url = url
        self.__apikey = apikey
        self.__secretkey = secretkey

    # OKCOIN期货行情信息
    def future_ticker(self,symbol,contractType):
        FUTURE_TICKER_RESOURCE = "/api/v1/future_ticker.do"
        params = ''
        if symbol:
            params += '&symbol=' + symbol if params else 'symbol=' +symbol
        if contractType:
            params += '&contract_type=' + contractType if params else 'contract_type=' +symbol
        return httpGet(self.__url,FUTURE_TICKER_RESOURCE,params)

    # OKCoin期货市场深度信息
    def future_depth(self,symbol,contractType,size): 
        FUTURE_DEPTH_RESOURCE = "/api/v1/future_depth.do"
        params = ''
        if symbol:
            params += '&symbol=' + symbol if params else 'symbol=' +symbol
        if contractType:
            params += '&contract_type=' + contractType if params else 'contract_type=' +symbol
        if size:
            params += '&size=' + size if params else 'size=' + size
        return httpGet(self.__url,FUTURE_DEPTH_RESOURCE,params)

    # OKCoin期货交易记录信息
    def future_trades(self,symbol,contractType):
        FUTURE_TRADES_RESOURCE = "/api/v1/future_trades.do"
        params = ''
        if symbol:
            params += '&symbol=' + symbol if params else 'symbol=' +symbol
        if contractType:
            params += '&contract_type=' + contractType if params else 'contract_type=' +symbol
        return httpGet(self.__url,FUTURE_TRADES_RESOURCE,params)

    # OKCoin期货指数
    def future_index(self,symbol):
        FUTURE_INDEX = "/api/v1/future_index.do"
        params=''
        if symbol:
            params = 'symbol=' +symbol
        return httpGet(self.__url,FUTURE_INDEX,params)

    # 获取美元人民币汇率
    def exchange_rate(self):
        EXCHANGE_RATE = "/api/v1/exchange_rate.do"
        return httpGet(self.__url,EXCHANGE_RATE,'')

    # 获取预估交割价
    def future_estimated_price(self,symbol):
        FUTURE_ESTIMATED_PRICE = "/api/v1/future_estimated_price.do"
        params=''
        if symbol:
            params = 'symbol=' +symbol
        return httpGet(self.__url,FUTURE_ESTIMATED_PRICE,params)

    # 期货全仓账户信息
    def future_userinfo(self):
        FUTURE_USERINFO = "/api/v1/future_userinfo.do?"
        params ={}
        params['api_key'] = self.__apikey
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_USERINFO,params)

    # 期货全仓持仓信息
    def future_position(self,symbol,contractType):
        FUTURE_POSITION = "/api/v1/future_position.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType
        }
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_POSITION,params)

    # 期货下单
    def future_trade(self,symbol,contractType,price='',amount='',tradeType='',matchPrice='',leverRate=''):
        FUTURE_TRADE = "/api/v1/future_trade.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType,
            'amount':amount,
            'type':tradeType,
            'match_price':matchPrice,
            'lever_rate':leverRate
        }
        if price:
            params['price'] = price
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_TRADE,params)

    # 期货批量下单
    def future_batchTrade(self,symbol,contractType,orders_data,leverRate):
        FUTURE_BATCH_TRADE = "/api/v1/future_batch_trade.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType,
            'orders_data':orders_data,
            'lever_rate':leverRate
        }
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_BATCH_TRADE,params)

    # 期货取消订单
    def future_cancel(self,symbol,contractType,orderId):
        FUTURE_CANCEL = "/api/v1/future_cancel.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType,
            'order_id':orderId
        }
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_CANCEL,params)

    # 期货获取订单信息
    def future_orderinfo(self,symbol,contractType,orderId,status,currentPage,pageLength):
        FUTURE_ORDERINFO = "/api/v1/future_order_info.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType,
            'order_id':orderId,
            'status':status,
            'current_page':currentPage,
            'page_length':pageLength
        }
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_ORDERINFO,params)

    # 期货逐仓账户信息
    def future_userinfo_4fix(self):
        FUTURE_INFO_4FIX = "/api/v1/future_userinfo_4fix.do?"
        params = {'api_key':self.__apikey}
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_INFO_4FIX,params)

    # 期货逐仓持仓信息
    def future_position_4fix(self,symbol,contractType,type1):
        FUTURE_POSITION_4FIX = "/api/v1/future_position_4fix.do?"
        params = {
            'api_key':self.__apikey,
            'symbol':symbol,
            'contract_type':contractType,
            'type':type1
        }
        params['sign'] = buildMySign(params,self.__secretkey)
        return httpPost(self.__url,FUTURE_POSITION_4FIX,params)



    def future_kline(self,symbol,type_,contract_type,size,since):
        """
        获取OKEx合约K线信息
        参数名	参数类型	必填	描述
            
        :param symbol: String	是	btc_usd ltc_usd eth_usd etc_usd bch_usd
        :param type: String	是	1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
        :param contract_type: String	是	合约类型: this_week:当周 next_week:下周 quarter:季度
        :param size: Integer	否(默认0)	指定获取数据的条数
        :param since: 否(默认0)	时间戳（eg：1417536000000）。 返回该时间戳以后的数据
        :return: [
    1440308760000,	时间戳
    233.38,		开
    233.38,		高
    233.27,		低
    233.37,		收
    186,		交易量
    79.70234956		交易量转化BTC或LTC数量
]
        """
        FUTURE_KLINE_RESOURCE = "/api/v1/future_kline.do"
        params = ''
        if symbol:
            params += '&symbol=' + symbol if params else 'symbol=' +symbol
        if type_:
            params += '&type=' + type_ if params else 'type=' + type_
        if contract_type:
            params += '&contract_type=' + contract_type if params else 'contract_type=' +contract_type
        if size:
            params += '&size=' + size if params else 'size=' + size
        if since:
            params += '&since=' + since if params else 'since=' + since

        return httpGet(self.__url, FUTURE_KLINE_RESOURCE, params)


############################################################################
'''
                      requests实现的OKEX期货API
'''
############################################################################
import requests                            # 用requests重写一遍期货接口,交易接口用需要签名，用上面的交易接口即可--陈常鸿
class OKexFutureByCCH:                   # 好好学习字符串的.join()踩坑了--陈常鸿
    def __init__(self,APIKEY,SECRETEKEY):
        self.__url='https://www.okex.com/api/v1/'
        self.__headers={
               "Content-type" : "application/x-www-form-urlencoded",
               }
        self.apiKey=APIKEY
        self.secreteKey=SECRETEKEY

    #------------------------------------------------------------------------
    def future_ticker(self,symbol='btc_usd',contractType='this_week'):
        '''OKEX期货行情信息'''
        TICKER_RESOURSE='future_ticker.do?'
        TICKER_URL=TICKER_RESOURSE+'symbol='+symbol+'&contract_type='+contractType
        print(TICKER_URL)
        result=requests.get(self.__url+TICKER_URL,headers=self.__headers).json()
        return result

    #------------------------------------------------------------------------
    def future_depth(self,symbol='btc_usd',contractType='this_week',size=10):
        '''OKEX期货深度信息'''
        DEPTH_RESOURSE='future_depth.do?'
        DEPTH_URL=DEPTH_RESOURSE+'symbol='+symbol+'&contractType='+contractType+'&size='+str(size)
        result=requests.get(self.__url+DEPTH_URL,headers=self.__headers).json()
        return result
    
    #-------------------------------------------------------------------------
    def future_trades(self,symbol='btc_usd',contractType='this_week'):
        '''OKEX交易记录信息'''
        TRADES_RESOURCE = "future_trades.do?"
        TRADES_URL=TRADES_RESOURCE+'symbol='+symbol+'&contractType='+contractType
        result=requests.get(self.__url.join(TRADES_URL),headers=self.__headers).json()
        return result

    #--------------------------------------------------------------------------
    def future_index(self,symbol='btc_usd'):
        ''' OKEX期货指数'''
        INDEX_RESOURSE = "future_index.do?"
        INDEX_URL=INDEX_RESOURSE+'symbol='+symbol
        result=requests.get(self.__url+INDEX_URL,headers=self.__headers).json()
        return result
    
    #--------------------------------------------------------------------------
    def exchange_rate(self):
        '''获取美元人民币汇率'''
        EXCHANGE_RATE = "exchange_rate.do"
        result=requests.get(self.__url+EXCHANGE_RATE,headers=self.__headers).json()
        return result
    
    #---------------------------------------------------------------------------
    def future_estimated_price(self,symbol='btc_usd'):
        '''交割预估价  注意：交割预估价只有交割前三小时返回'''
        ESTIMATED_PRICE = "future_estimated_price.do?"
        ESTIMATED_URL=ESTIMATED_PRICE+'symbol='+symbol
        result=requests.get(self.__url+ESTIMATED_URL,headers=self.__headers).json()
        return result

    #-----------------------------------------------------------------------------
    def future_kline(self,symbol='btc_usd',type_='1min',contractType='this_week',size=0,since=0):
        '''获取OKEx合约K线信息
            type : 1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
            contractType : 合约类型: this_week:当周 next_week:下周 quarter:季度
            size : 指定获取数据的条数(int)
            since : 时间戳（eg：1417536000000）返回该时间戳以后的数据(long)
        '''
        KLINE_RESOURSE='future_kline.do?'
        if size==0 and since==0:
            KLINE_URL=KLINE_RESOURSE+'symbol='+symbol+'&type='+type_+'&contractType='+contractType
        else:
            KLINE_URL=KLINE_RESOURSE+'symbol='+symbol+'&type='+type_+'&contractType='+contractType+'&size='+str(size)+'&since'+str(since)
        result=requests.get(self.__url.join(KLINE_URL),headers=self.__headers).json()
        return result
    
    #-------------------------------------------------------------------------------
    def future_hold_amount(self,symbol='btc_usd',contractType='this_week'):
        '''获取当前可用合约总持仓量'''
        HOLD_AMOUNT_RESOURSE='future_hold_amount.do?'
        HOLD_AMOUNT_URL=HOLD_AMOUNT_RESOURSE+'symbol='+symbol+'&contractType='+contractType
        result=requests.get(self.__url+HOLD_AMOUNT_URL,headers=self.__headers).json()
        return result

    #-------------------------------------------------------------------------------
    def future_price_limit(self,symbol='btc_usd',contractType='this_week'):
        '''获取合约最高限价和最低限价'''
        PRICE_LIMIT_RESOURSE='future_price_limit.do?'
        PRICE_LIMIT_URL=PRICE_LIMIT_RESOURSE+'symbol='+symbol+'&contractType='+contractType
        result=requests.get(self.__url+PRICE_LIMIT_URL,headers=self.__headers).json()
        return result

    #----------------------------------------------------------------------------
    def future_userinfo(self):
        '''期货全仓账户信息,访问频率 5次/2秒'''
        pass
    
    #----------------------------------------------------------------------------
    def future_position(self):
        '''获取用户持仓获取OKEX合约账户信息 （全仓）访问频率 10次/2秒'''
        pass
    
    #----------------------------------------------------------------------------
    def future_trade(self):
        '''合约下单 访问频率 20次/2秒(按币种单独计算)'''
        pass

    #----------------------------------------------------------------------------
    def future_trades_history(self):
        '''获取OKEX合约交易历史（非个人）访问频率 访问频率 1次/120秒'''
        pass
    
    #----------------------------------------------------------------------------
    def future_batch_trade(self):
        '''批量下单 访问频率 10次/2秒 最多一次下1-5个订单（按币种单独计算）'''

    #----------------------------------------------------------------------------
    def future_cancel(self):
        '''取消合约订单   访问频率 10次/2秒，最多一次撤1-5个订单（按币种单独计算）'''
        pass
    
    #----------------------------------------------------------------------------
    def future_order_info(self):
        '''获取合约订单信息 访问频率 10次/2秒'''
        pass
    
    #----------------------------------------------------------------------------
    def future_orders_info(self):
        '''批量获取合约订单信息 访问频率 10次/2秒'''
        pass
    
    #----------------------------------------------------------------------------
    def future_userinfo_4fix(self):
        '''获取逐仓合约账户信息 访问频率 5次/2秒'''
        pass
    
    #-----------------------------------------------------------------------------
    def future_position_4fix(self):
        ''' 逐仓用户持仓查询  访问频率 10次/2秒'''
        pass
    
    #-----------------------------------------------------------------------------
    def future_explosive(self):
        '''获取合约爆仓单  '''
        pass
    
    #-----------------------------------------------------------------------------
    def future_devolve(self):
        '''个人账户资金划转'''
        pass
    